package promote.brozen.netty.jav.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.spi.AsynchronousChannelProvider;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.LockSupport;

/**
 * @author Brozen
 * @date 2020/9/27 1:44 PM
 * @email brozen@qq.com
 */
public class AioClient {

    AsynchronousSocketChannel asc;

    public void connect() throws IOException {
//        asc = AsynchronousSocketChannel.open();
        AioClientConnector aioClientConnector = new AioClientConnector(this);
        InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 8090);

        // 配置线程池
        AsynchronousChannelProvider provider = AsynchronousChannelProvider.provider();
        AsynchronousChannelGroup acg = provider.openAsynchronousChannelGroup(Executors.newSingleThreadExecutor(r -> {
            Thread thread = new Thread(r);
            thread.setName("SCP-Client");
            return thread;
        }), 0);// warning 这里的第二个参数initialSize设置为1的话，启动之后无法连接，不知道为啥
        asc = provider.openAsynchronousSocketChannel(acg);

        // 连接到服务端
        asc.connect(serverAddress, this, aioClientConnector);

        LockSupport.park();
    }

    public static void main(String[] args) throws IOException {
        new AioClient().connect();
    }

}
